import cookie from 'js-cookie'
import cookieKeys from '@/const/cookie-keys'
import {adminUser} from '@/const/api.js'
import meta from '@/const/meta.js'
import {getXpaasTag} from '@/const/api.js'
import {userMenuTree} from '@/const/api.js'
import {loginByUsername} from '@/const/api.js'

const cookiePath = process.env.COOKIE_PATH

const isObject = value =>
  Object.prototype.toString.call(value) === '[object Object]'

export const state = () => ({
  userId: '',
  token: '',
  tenantId: '',
  username: '',
  workNumber: '',
  user: {},
  meta: {},
  permission: {
    thirdId: '',
    menuList: [
      {
        id: 1,
        name: '排班',
        url: '/scheduling/scheduling',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 2,
        name: '班次管理',
        url: '/shifts/shifts',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      // {
      //   id: 3,
      //   name: '班组管理',
      //   url: '/team/team',
      //   myChilds: [], // 为啥不用children 不解释
      //   meta: {
      //   },
      // },
      {
        id: 4,
        name: '排班管理',
        url: '/SM/SM',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 5,
        name: '调休管理',
        url: '/breakoff/continued',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 6,
        name: '剩休管理',
        url: '/rest/type',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 7,
        name: '调班调度管理',
        url: '/dispatch/quota',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 8,
        name: '节假日管理',
        url: '/holiday/holiday',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 9,
        name: '查询与统计',
        url: '/SandS/table',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 10,
        name: '考勤管理',
        url: '/CWA/CWA',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
      },
      {
        id: 11,
        name: '设置月统计报表列',
        url: '/setting/monthtableconfig',
        myChilds: [], // 为啥不用children 不解释
        meta: {},
        hidden: true,
      },
    ],
    menuReady: true, // 侧边栏loading
    spaName: meta.spaName,
  },
  setting: {
    collapse: false, // 是否收缩侧边栏
  },
})

export const mutations = {
  userMenuTreeReady(state, payload) {
    state.permission.menuReady = payload
  },
  login(state, payload) {
    cookieKeys.forEach(key => {
      state[key] = payload[key] ? payload[key] : ''
      cookie.set(key, payload[key] ? payload[key] : '', {
        path: cookiePath,
      })
    })
  },
  logout(state) {
    cookieKeys.forEach(key => {
      state[key] = ''
      cookie.remove(key, {
        path: cookiePath,
      })
    })
    // 清空state，跳转到login页的逻辑交给路由守卫
    location.reload()
  },
  update(state, payload) {
    Object.keys(payload).forEach(k => {
      if (isObject(payload[k])) {
        state[k] = Object.assign(state[k], payload[k])
      } else {
        state[k] = payload[k]
      }
    })
  },
  setToken(state, payload) {
    state.token = payload
  },
}

export const actions = {
  // 用户名账号登录
  async loginByUsername({commit, dispatch}, userInfo) {
    try {
      const res = await this.$axios.$post(loginByUsername, userInfo, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
      if (res.state == 200) {
        const data = {
          userId: res.data.id,
          username: res.data.name,
          password: res.data.password,
          roleId: res.data.role[0].id,
        }
        commit('login', data)
        commit('update', {user: data})
        return data
      }
    } catch (err) {
      // const data      = {
      //   userId:   userInfo['username'],
      //   username: '谷歌',
      //   password: userInfo['username'],
      //   roleId:   userInfo['username'],
      // }
      // commit('login', data)
      // commit('update', {user: data})
      return err
    }
  },
  async loginByAuthorization({commit, dispatch}, Authorization) {
    try {
      const res = await this.$axios.$post(
        loginByUsername,
        {Authorization},
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        },
      )
      let obj = res.data
      const data = {
        userId: obj.userId,
        username: obj.userName,
        password: obj.password,
        roles: obj.roles,
        email: obj.email,
        mobile: obj.mobile,
        workNumber: obj.workNumber,
        token: Authorization,
      }
      commit('login', data)
      commit('update', {user: data})
      return data
    } catch (err) {
      return err
    }
  },
  // 获取头部列表的thirdId
  async fetchThirdId({commit, dispatch, state}, {tenantId}) {
    let {payload} = await this.$axios.$get(
      `${adminUser}${tenantId ? `?tenantId=${tenantId}` : ''}`,
    )
    const {thirdId} = payload || {}

    commit('update', {
      permission: {thirdId},
    })

    try {
      const headMenu = await dispatch('fetchHeadMenu', {thirdId})

      // 根据当前的项目名称来请求左侧菜单
      for (let item of headMenu) {
        if (item.name === state.permission.spaName) {
          dispatch('fetchUserMenuTree', {appId: item.id})
          break
        }
      }
    } catch (e) {
      console.error('fetchHeadMenu error: ', e)
    }
  },
  // 根据thirdId获取头部导航栏列表
  async fetchHeadMenu({commit, dispatch}, {thirdId}) {
    let headMenuListRes = await this.$axios.$get(getXpaasTag(thirdId))
    const payload = headMenuListRes.payload || []
    commit('update', {
      permission: {headMenuList: payload},
    })
    return payload
  },
  // 根据appId获取左侧菜单, 并设置当前的mainHead值
  async fetchUserMenuTree({commit}, {appId}) {
    let userMenuTreeRes = await this.$axios.$get(userMenuTree(appId))
    const payload = userMenuTreeRes.payload || []
    // 获取路由对应的页面名
    commit('update', {
      permission: {menuList: payload},
    })
    commit('userMenuTreeReady', true)
  },
}
